<?php
/**
 * Created by PhpStorm.
 * User: front
 * Date: 2018/8/7
 * Time: 17:37
 */

namespace App\Api\Admin\Controllers;

use App\Exceptions\ApiException;
use App\Models\Admin\Log;
use App\Models\Admin\Permission;
use App\Models\Admin\Role;
use App\Services\Admin;
use Illuminate\Http\Request;

class AdminController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
        if ($this->user['permissions'] !== '*' && !isset($this->user['permissions']['admin_permission'])) {
            throw new ApiException('没有权限', 0);
        }
    }

    /**
     * 角色列表
     * @return array
     */
    public function roleList()
    {
        $roles = Role::get(['name', 'permissions'])->toArray();

        foreach ($roles as &$role) {
            if ($role['permissions'] === '*') {
                $permissions = Permission::get(['name', 'name_zh']);
            } else {
                $permissions = Permission::whereIn('id', explode(',', $role['permissions']))->get(['name', 'name_zh']);
            }

            $role['permissions'] = Admin::parsePermissions($permissions);
        }
        unset($role);

        return json_success('ok', $roles);
    }

    /**
     * 编辑角色及权限
     * @param Request $request
     * @return array
     */
    public function editRolePermission(Request $request)
    {
        $role_id = (int) $request->input('role_id');
        $name = IT('name', true, '请输入角色名称');
        $ids = IT('ids', true, '请选择对应的权限');
        $ids = $this->checkIds($ids);
        $permissions = Permission::whereIn('id', $ids)->get(['id', 'name', 'name_zh']);
        $ids = $this->parseIds($permissions);

        if (!$ids) {
            return json_error('参数有误,权限有误');
        }

        if ($role_id) {
            $role = Role::find($role_id);
            if (!$role || $role->name === '超级管理员') {
                return json_error('参数有误,角色有误');
            }
            if ($role->name !== $name && Role::where('name', $name)->first()) {
                return json_error('参数有误,角色名称已存在');
            }
        }

        if (!isset($role)) {
            if (Role::where('name', $name)->first()) {
                return json_error('参数有误,角色名称已存在');
            }
            $role = new Role;
        }

        (new Log)->add($this->user, $role_id ? ('将角色名称“'. $role->name .'”改为“' . $name . '”, 权限由“' . $role->permissions . '”改为“' . $ids . '”') : ('添加新角色, 名称为“'.$name.'”, 权限为“'.$ids.'”'));

        $role->name = $name;
        $role->permissions = $ids;
        $role->save();

        return json_success('ok');
    }

    /**
     * 权限列表
     * @return array
     */
    public function permissionList()
    {
        $permissions = Permission::get(['id', 'name', 'name_zh']);

        return json_success('ok', $permissions);
    }

    /**
     * 日志列表
     * @param Request $request
     * @return array
     */
    public function log(Request $request)
    {
        $page = max(1, (int) $request->input('page'));
        $uid = (int) $request->input('uid');
        $pagesize = (int) $request->input('pagesize');
        $pagesize = $pagesize ?: 10;

        $fields = ['id', 'username', 'action', 'create_at'];
        $offset = ($page - 1) * $pagesize;

        if ($uid) {
            $logs = Log::where('uid', $uid)->take($pagesize)->skip($offset)->orderBy('id', 'desc')->get($fields);
            $total = Log::where('uid', $uid)->count();
        } else {
            $logs = Log::take($pagesize)->skip($offset)->orderBy('id', 'desc')->get($fields);
            $total = Log::count();
        }

        $totalPage = ceil($total / $pagesize);

        $logs = $logs ?: [];

        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage, 'list' => $logs]);
    }

    /**
     * 转化id，去重
     * @param string $ids
     * @return array
     */
    private function checkIds($ids = '')
    {
        $ids = explode(',', $ids);
        foreach ($ids as &$id) {
            $id = (int) $id;
        }

        return array_unique($ids);
    }

    /**
     * 从权限中解析出权限id
     * @param $permissions
     * @return null|string
     */
    private function parseIds($permissions)
    {
        $ids = [];

        foreach ($permissions as $permission) {
            if ($permission instanceof Permission) {
                $permission = $permission->toArray();
            }
            $ids[] = $permission['id'];
        }

        if (empty($ids)) {
            return null;
        }

        return implode(',', $ids);
    }
}